package emd24.telstudyresources;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.concurrent.ExecutionException;

import org.json.*;

import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
/**
 * This activity displays all the available question banks that are able to
 * be used.
 * 
 * @author Evan Dyke, William Easton
 */
public class StudyTableofContents extends Activity {

	private ArrayList<BankHeader> head = new ArrayList<BankHeader>();

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_study_tableof_contents);
		setTitle("Browse Questions");
		Bundle b = this.getIntent().getExtras();
		this.head = b.getParcelableArrayList("header");
		ListView v = (ListView) this.findViewById(R.id.table_of_contents);
		v.setAdapter(new ContentsAdapter(this, head));
		v.setOnItemClickListener(new OnItemClickListener(){

			@Override
			public void onItemClick(AdapterView<?> parent, View view, int pos,
					long id) {
				try {
					openBank(pos);
				} catch (InterruptedException e) {
					errorOpen();
				} catch (ExecutionException e) {
					errorOpen();
				}
			}
		});
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.study_tableof_contents, menu);
		return true;
	}
	
	/**
	 * Opens a given question bank and starts StudyModeActivity.
	 * 
	 * @param pos the index of the question bank
	 * @throws InterruptedException
	 * @throws ExecutionException
	 */
	private void openBank(int pos) throws InterruptedException, ExecutionException {
		Intent i = new Intent(this,StudyModeActivity.class);
		Quiz bank = null;
		QuizLoader q = new QuizLoader();
		q.execute(this.head.get(pos).getUrl());
		bank = q.get();
		if(bank == null){
			errorOpen();
			return;
		}
		i.putExtra("bank",bank);
		startActivity(i);
	}
	/**
	 * Displays an error message if trouble opening bank.
	 */
	private void errorOpen(){
		new AlertDialog.Builder(this).setMessage(R.string.bank_error).
		setNeutralButton("Ok", new DialogInterface.OnClickListener() {

			// Set listener for when yes button is clicked, exit activity
			public void onClick(DialogInterface arg0, int arg1) {

			}
		}).show();
	}
	/**
	 * This is an adapter for the table of contents.
	 * 
	 * @author Evan Dyke
	 *
	 */
	private class ContentsAdapter extends BaseAdapter {

		ArrayList<BankHeader> banks;

		private ContentsAdapter(Context c, ArrayList<BankHeader> banks){
			this.banks = banks;
			LayoutInflater.from(c);

		}

		@Override
		public int getCount() {
			return this.banks.size();
		}

		@Override
		public Object getItem(int position) {
			return this.banks.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			TextView name;
			if(convertView == null){
				LayoutInflater inflater = LayoutInflater.from(parent.getContext());
				convertView = inflater.inflate(R.layout.tablecontents_row_view, parent, false);

			} 
			name = (TextView) convertView.findViewById(R.id.bank_title);
			name.setText(this.banks.get(position).getName());


			return convertView;
		}

	}
	
	/**
	 * Asynchronusly creates a Quiz from a JSON file
	 * stored at a given URL
	 * 
	 * @authors Evan Dyke, William Easton
	 *
	 */
	private class QuizLoader extends AsyncTask<String, Void, Quiz>{

		ProgressDialog d;

		protected void onPreExecute() {
			super.onPreExecute();
			d = new ProgressDialog(StudyTableofContents.this);
			d.setMessage("Loading Question Bank...");
			d.setIndeterminate(false);
			d.setProgressStyle(ProgressDialog.STYLE_SPINNER);
			d.setCancelable(true);
			d.show();
		}
		protected Quiz doInBackground(String... params) {
			String parsedResult = null;
			try {
				// Get the JSON from online
				Log.e("QuizLoader"," QuizLoader: Starting Parse");
				URL url = new URL(params[0]);
				Log.e("QuizLoader"," QuizLoader: Starting Connection");
				HttpURLConnection conn = (HttpURLConnection) url.openConnection();
				conn.setDoInput(true);
				Log.e("QuizLoader"," QuizLoader:  Opening Connection");
				conn.connect(); //Open connection, code will fail here if there is no network connection
				InputStream is = conn.getInputStream();
				Log.e("QuizLoader"," QuizLoader:  Closing Connection");
				parsedResult = MainActivity.getStringFromInputStream(is);	
				Log.e("QuizLoader: Parsed", "QuizLoader " + parsedResult);
				Log.e("QuizLoader: Parsed", "QuizLoader " + parsedResult);
				is.close();
				JSONObject quizJS = new JSONObject(parsedResult);
				// Create the quiz
				return new Quiz(quizJS, quizJS.getJSONArray("questions").length(), false);
			} catch (MalformedURLException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			} catch (JSONException e) {
				e.printStackTrace();
			}
			return null;
		}
		protected void onPostExecute(Quiz q){
			d.dismiss();
		}
	}
}
